import { FormField } from '../types'

export function generateValidationScript(fields: FormField[]): string {
  return fields
    .map(field => {
      switch (field.type) {
        case 'tags':
          return generateTagsValidation(field)
        case 'textarea':
        case 'input':
        default:
          return generateTextValidation(field)
      }
    })
    .join('\n')
}

function generateTagsValidation(field: FormField): string {
  return `
    const ${field.id}Input = document.getElementById('${field.id}');
    const ${field.id} = ${field.id}Input ? JSON.parse(${field.id}Input.value || '[]') : [];
    formData.${field.id} = ${field.id};
    log('${field.label}数量: ' + ${field.id}.length);
    ${field.required ? `if (${field.id}.length === 0) { isValid = false; }` : ''}
  `
}

function generateTextValidation(field: FormField): string {
  return `
    const ${field.id} = document.getElementById('${field.id}').value.trim();
    formData.${field.id} = ${field.id};
    log('${field.label}长度: ' + ${field.id}.length);
    ${field.required ? `if (!${field.id}) { isValid = false; }` : ''}
  `
}
